<template>
  <el-upload
    class="upload"
    action="#"
    :http-request="(data) => {upload(data)}"
    accept="image/jpeg,image/png"
    :show-file-list="false"
  >
    <div v-if="url" :style="{'width': width + 'px','height': height + 'px'}">
      <img :height="height" :src="cdn + url" class="avatar" alt="">
    </div>
    <div v-else :style="{'width': width + 'px','height': height + 'px'}">
      <i class="el-icon-plus icon"></i>
    </div>
  </el-upload>
</template>

<script>
import { putObejct } from '../../../utils/oss'
import { CLOUD_OSS_CDN } from '../../../../config'
export default {
  name: 'Uploader',
  props: {
    url: {
      type: String,
      default: null
    },
    width: {
      type: Number,
      default: 266
    },
    height: {
      type: Number,
      default: 200
    },
    oss: {
      type: String,
      default: 'image'
    }
  },
  data() {
    return {
      cdn: CLOUD_OSS_CDN
    }
  },
  methods: {
    upload(data) {
      if (this.validate(data.file)) {
        const that = this
        putObejct(data.file, this.oss, function(res) {
          const url = res.Location
          // console.log(url.slice(url.indexOf('/')))
          that.$emit('callback', url.slice(url.indexOf('/') + 1))
        })
      }
    },
    validate(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
    .upload /deep/ .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .upload /deep/ .el-upload:hover {
        border-color: #409EFF;
    }
    .upload /deep/ .el-upload:hover div .icon{
        color: #409EFF;
    }
    .icon {
        position: absolute;
        top: calc(50% - 14px);
        left: calc(50% - 14px);
        font-size: 28px;
        color: #8c939d;
    }
    .avatar {
        display: block;
    }
</style>
